<template>
  <!--用户管理-->
  <div class="app-container">
    <el-form class="jc_search_wrap" v-model="searchList">
      <label>用户名</label><el-input></el-input>
      <label>性别</label><el-input></el-input>
      <label>状态</label><el-input></el-input>
      <el-button @click="searchRows"><i class="el-icon-search"></i>查询</el-button>
    </el-form>
    <el-button-group class="jc_btn_wrap jc_btn_left">
      <el-button @click="createRow"><i class=""></i>新增用户</el-button>
      <el-button @click="editRow"><i class=""></i>编辑</el-button>
      <el-button @click="deleteRow"><i class=""></i>删除</el-button>
    </el-button-group>
   <el-table :height="tableHeight" :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row class="jc_table_wrap"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="80px">
      </el-table-column>
      <el-table-column label='查看详情'>
        <template scope="scope">
          <el-button type="text" @click="detailRow(scope.row)">详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label='id' v-if="false">
        <template scope="scope">
          {{scope.row.id}}
        </template>
      </el-table-column>
      <el-table-column label='用户名'>
        <template scope="scope">
          {{scope.row.username}}
        </template>
      </el-table-column>
      <el-table-column label="部门">
        <template scope="scope">
          {{scope.row.deptName}}
        </template>
      </el-table-column>
      <el-table-column label="邮箱">
        <template scope="scope">
          {{scope.row.email}}
        </template>
      </el-table-column>
      <el-table-column label="手机">
        <template scope="scope">
          {{scope.row.mobile}}
        </template>
      </el-table-column>
     <el-table-column label="性别">
       <template scope="scope">
         {{scope.row.ssex==="0"?"男":"女"}}
        </template>
     </el-table-column>
     <el-table-column label="创建时间">
       <template scope="scope">
         {{scope.row.crateTime}}
        </template>
     </el-table-column>
     <el-table-column label="状态">
       <template scope="scope">
         {{scope.row.status==="1"?"有效":"无效"}}
        </template>
     </el-table-column>
    </el-table>
    <el-pagination layout="prev, pager, next" :total="total" @current-change="changePage" :page-size="10" :current-page="currentPage"/>
    <!--新建-->
     <el-dialog title="新建用户" :visible.sync="create_visible" class="jc_dialog_wrap">
       <el-form :model="form_create" label-width="120px">
         <el-form-item label="用户名">
           <el-input v-model="form_create.username"></el-input>
         </el-form-item>
         <el-form-item label="密码">
           <el-input v-model="form_create.password"></el-input>
         </el-form-item>
         <el-form-item label="邮箱">
           <el-input v-model="form_create.email"></el-input>
         </el-form-item>
         <el-form-item label="手机">
           <el-input v-model="form_create.mobile"></el-input>
         </el-form-item>
         <el-form-item label="角色">
           <el-checkbox-group v-model="roles">
             <el-checkbox :model="roleList" v-for="item in roleList" :label="item.roleId" :value="item.roleName" :key="item.roleId">{{item.roleName}}</el-checkbox>
           </el-checkbox-group>
         </el-form-item>
         <el-form-item label="性别">
           <el-radio-group v-model="ssex">
             <el-radio :label="0">男</el-radio>
             <el-radio :label="1">女</el-radio>
           </el-radio-group>
         </el-form-item>
         <el-form-item label="部门">
           <el-tree style="width: 300px;":data="treeDeptData" leafOnly show-checkbox node-key="deptId" :props="defaultProps" ref="tree" @check-change="handleClick" :check-strictly="true"></el-tree>
         </el-form-item>
       </el-form>
         <div slot="footer" class="dialog-footer">
           <el-button type="primary" @click="submitCreateForm">确定</el-button>
           <el-button @click="create_visible=false">取消</el-button>
         </div>
     </el-dialog>
    <!--编辑-->
    <el-dialog title="编辑用户" :visible.sync="edit_visible" class="jc_dialog_wrap">
      <el-form :model="form_edit" label-width="120px">
        <el-form-item label="id" v-if="false">
          <el-input v-model="form_edit.userId"></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="form_edit.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form_edit.email"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="form_edit.mobile"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox-group v-model="roles">
            <el-checkbox :model="roleList" v-for="item in roleList" :label="item.roleId" :value="item.roleName" :key="item.roleId">{{item.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="ssex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门">
          <el-tree style="width: 300px;":data="treeDeptData" leafOnly show-checkbox node-key="deptId" :props="defaultProps" ref="tree" :accordion="true" :default-checked-keys="editDept" :default-expanded-keys="editDept" @check-change="handleClick" :check-strictly="true"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm">确定</el-button>
        <el-button @click="edit_visible=false">取消</el-button>
      </div>
    </el-dialog>
    <!--详情-->
    <el-dialog title="用户详情" :visible.sync="detail_visible" class="jc_dialog_wrap">
      <el-form :model="form_detail" label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="form_detail.loginName" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form_detail.password" disabled></el-input>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="form_detail.realName" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form_detail.email" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="form_detail.phoneNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="工号">
          <el-input v-model="form_detail.workNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-input v-model="form_detail.status" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detail_visible=false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import * as User from "../../api/systemApi/user";
  import * as Role from "../../api/systemApi/role";
  import * as Dept from "../../api/systemApi/department";

  export default {
    components: {

    },
    data() {
      return {
        searchList: {
          status : "",
        },
        list: null,
        total: 0,
        currentPage: 1,
        create_visible: false,
        detail_visible: false,
        edit_visible: false,
        relation_visible: false,
        form_create: {},
        ssex: 0,
        form_detail: {},
        form_edit: {},
        form_relation: {},
        userStatus: [],
        multipleSelection: [],
        roles: [],
        roleList: [],
        treeDeptData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        editDept: [],
        i_tree:0, //单选时用
      }

    },
    created() {
      this.fetchData();
      this.getDeptList();//tree如果不在这里加载，在编辑框打开加载，那么打开时并不能加载成功，也就无法给出默认勾选项
    },
    methods: {
      fetchData(p=1) {
        this.listLoading = true;
        var params = this.searchList;
        params.pageNum = this.currentPage = p;
        params.pageSize = 10;
        User.getUserList(params).then(data => {
          this.list = data.rows;
          this.total = data.total;
          this.listLoading = false;
        })

      },
      searchRows() {
        this.fetchData()
      },
      emptyInputs() {
        this.searchList = {};
        this.fetchData()
      },
      createRow() {
        this.create_visible = true;
        this.getRoleList();
        this.form_create = {}
      },
      submitCreateForm() {
        var keys = this.$refs.tree.getCheckedKeys().splice(-1,1);
        //console.log('keys',keys);
        this.form_create.deptId = keys.join(',');  //只能选择一个部门，所以以最后一个勾选的为准
        this.form_create.roles = this.roles.join(',');
        this.form_create.ssex = this.ssex;
        //console.log('this.form_create',this.form_create);
        User.createUser(this.form_create).then(data => {
          this.create_visible = false;
          this.fetchData();
        })
      },
      editRow() {
        if(this.$refs.trees) { //只有第二次打开dialog才会加载好树形结构
          this.$refs.trees.setCheckedNodes([]);//清空已选的
          this.editDept = []; //清空展开项
        }
        if(this.multipleSelection.length === 0) {
          alert('请先勾选行');
        }else if(this.multipleSelection.length >= 2) {
          alert('每次最多勾选一行');
        }else if(this.multipleSelection.length === 1){
          var param = {userId:this.multipleSelection[0].userId};
          User.searchUserRow(param).then(data => {
            this.edit_visible = true;
            this.form_edit = data.msg;
            this.getRoleList();
            this.roles = data.msg.roleIds; // 角色的勾选
            //勾选部门
            //只有第二次打开dialog才会加载好树形结构
            /*if( this.$refs.trees) {//第二次打开时 勾选
              this.$refs.trees.setCheckedKeys([data.msg.deptId]);
              this.editDept.push(data.msg.deptId); //第二次打开之后 的展开项
            }else {
              this.editDept.push(data.msg.deptId); //第一次打开时，勾选
            }*/
            /*因为部门已经删除，现在看到同名的部门，id不一定相同，报错，等数据好了再显示*************************************************************************/
          })
        }
      },
      submitEditForm() {
        var keys = this.$refs.tree.getCheckedKeys().splice(-1,1);
        this.form_edit.deptId = keys.join(',');  //只能选择一个部门，所以以最后一个勾选的为准
        this.form_edit.rolesSelect = this.roles.join(',');
        this.form_edit.ssex = this.ssex;
        console.log('this.form_edit',this.form_edit);
        User.updateUser(this.form_edit).then(data => {
          this.edit_visible = false;
          this.fetchData(this.currentPage);
        })
      },
      detailRow() {
      },
      deleteRow() {
        if(this.multipleSelection.length === 0) {
          alert('请先勾选行');
        }else if(this.multipleSelection.length >= 2) {
          alert('每次最多勾选一行');
        }else if(this.multipleSelection.length === 1){
          this.$confirm('是否删除该条数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            User.delRow({ids:this.multipleSelection[0].userId}).then(data => {
              this.fetchData(this.currentPage);
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            })

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });

        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleClick(data,checked, node) {
        /*console.log('data',data);
        console.log('checked',checked);
        console.log('node',node);*/
        this.i_tree++;
        if(this.i_tree%2==0){
          if(checked){
            this.$refs.tree.setCheckedNodes([]);
            this.$refs.tree.setCheckedNodes([data]);
            //交叉点击节点
          }else{
            this.$refs.tree.setCheckedNodes([]);
            //点击已经选中的节点，置空
          }
        }
      },
      getStatus() {
        this.userStatus = [
          {name: '可用',value: 'enable'},
          {name: '不可用',value: 'disable'}
        ];
      },
      getRoleList() {
        Role.getRoleList().then(data => {
            this.roleList = data.rows;
        })
      },
      getDeptList() {
        this.treeDeptData = [];  //先清空数据
        function getTree(data,parentData) {
          var childrenArr = [] //所有非一级父元素的集合
          for(var i=0;i<data.length;i++) {
            var obj = {};
            var objChildrens = {};
            if(data[i].parentId === 0) { //parentId是0,说明是父元素，它的里面可能会有子集
              obj.label=data[i].deptName;
              obj.deptId=data[i].deptId;
              obj.parentId=data[i].parentId;
              obj.children = [];
              parentData.push(obj);
            }else { //找到所有的子集 装在childrenArr
              objChildrens.label=data[i].deptName;
              objChildrens.deptId=data[i].deptId;
              objChildrens.parentId=data[i].parentId;
              objChildrens.children = [];
              childrenArr.push(objChildrens);
            }
          }
          //二级菜单装入一级菜单
          var lever2Arr = [];
          for(var i in parentData) {
            for(var j in childrenArr) {
              if(parentData[i].deptId === childrenArr[j].parentId) {
                parentData[i].children.push(childrenArr[j]);
                lever2Arr.push(childrenArr[j])
              }
            }
          }
          getTreeChildren(parentData,childrenArr,lever2Arr);

        }
        function getTreeChildren(parentData,childrenArr,lever2Arr) {
          //找到三级菜单
          var lever3Arr = [];
          for(var i in childrenArr) {
            for(var j in lever2Arr) {
              if(lever2Arr[j].deptId === childrenArr[i].parentId) {
                lever3Arr.push(childrenArr[i])
              }
            }
          }
          //三级放入
          for(var i in lever3Arr) {
            for(var j in parentData) {
              for(var k in parentData[j].children) {
                if(parentData[j].children[k].deptId === lever3Arr[i].parentId) {
                  parentData[j].children[k].children.push(lever3Arr[i]);
                  getTreeChildren(parentData[j].children,childrenArr,lever3Arr);
                }
              }
            }
          }


        }
        Dept.getDepartmentList().then(data => {
          //console.log('获得的tree数据',data);
          getTree(data,this.treeDeptData);
          //console.log('整理后的tree数据',this.treeDeptData);
        })
      },
      changePage(p) {
        this.fetchData(p)
      }
    },
    computed: {
      tableHeight() {
        const filterHeight = 28
        var tableHeight = this.getTableHeight(filterHeight)
        return tableHeight;
      }
    }
  }
</script>
